package com.lp.zyll.filter;

import com.lp.zyll.constant.LpConstant;
import com.lp.zyll.domain.User;
import com.lp.zyll.redis.RedisCRUD;
import com.lp.zyll.security.LoginUser;
import com.lp.zyll.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * token过滤器 验证token有效性
 *
 * @author xxx
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    private static final Logger log = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);
//    @Autowired
//    private TokenService tokenService ;

    @Autowired
    RedisCRUD redisCRUD;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
//        //跨域
//        ServletUtils.setCross(response);
        String authorization = request.getHeader(LpConstant.TOKEN_HEADER);
        if( ! ObjectUtils.isEmpty(authorization)){
            LoginUser loginUser = redisCRUD.getObject(authorization, LoginUser.class);
            String path = request.getRequestURI();
            log.info("request url : " + path);
            if ( ! ObjectUtils.isEmpty(loginUser) ) {
                //如果没过期 则 刷新令牌有效期
                redisCRUD.expire(authorization,LpConstant.tokenTime);
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }

        chain.doFilter(request, response);
    }

}
